<script>
import { deepClone } from "@/utils/index";
import render from "@/components/render/render.js";

const ruleTrigger = {
  "el-input": "blur",
  "el-input-number": "blur",
  "el-select": "change",
  "el-radio-group": "change",
  "el-checkbox-group": "change",
  "el-cascader": "change",
  "el-time-picker": "change",
  "el-date-picker": "change",
  "el-rate": "change",
};

const layouts = {
  emptyDiv(h, scheme) {
    return (<div placeholder-form-id={scheme.__config__.formId} ></div>)
  },
  vHtml(h, scheme) {
    const config = scheme.__config__
    // return ( <div domPropsInnerHTML={scheme.__config__.defaultValue}></div> )
    return (
      <el-col span={config.span} offset={config.offset} style="padding:0;margin:0;">
        <div domPropsInnerHTML={config.defaultValue}></div>
      </el-col>
    )
  },
  colFormItem(h, scheme) {
    const config = scheme.__config__;
    const listeners = buildListeners.call(this, scheme);

    let labelWidth = config.labelWidth ? `${config.labelWidth}px` : null;
    if (config.showLabel === false) labelWidth = "0";
    return (
      <el-col span={config.span}>
        <el-form-item
          label-width={labelWidth}
          prop={scheme.__vModel__}
          label={config.showLabel ? config.label : ""}
        >
          <render conf={scheme} {...{ on: listeners }} />
        </el-form-item>
      </el-col>
    );
  },
  rowFormItem(h, scheme) {
    let child = renderChildren.apply(this, arguments);
    if (scheme.type === "flex") {
      child = (
        <el-row
          type={scheme.type}
          justify={scheme.justify}
          align={scheme.align}
        >
          {child}
        </el-row>
      );
    }
    return (
      <el-col span={scheme.span}>
        <el-row gutter={scheme.gutter}>{child}</el-row>
      </el-col>
    );
  },
};

function renderFrom(h) {
  const { formConfCopy } = this;

  return (
    <el-row gutter={formConfCopy.gutter}>
      <el-form
        size={formConfCopy.size}
        label-position={formConfCopy.labelPosition}
        disabled={formConfCopy.disabled}
        label-width={`${formConfCopy.labelWidth}px`}
        ref={formConfCopy.formRef}
        // model不能直接赋值 https://github.com/vuejs/jsx/issues/49#issuecomment-472013664
        props={{ model: this[formConfCopy.formModel] }}
        rules={this[formConfCopy.formRules]}
      >
        {renderFormItem.call(this, h, formConfCopy.fields)}
        {formConfCopy.formBtns && formBtns.call(this, h)}
      </el-form>
    </el-row>
  );
}

function formBtns(h) {
  return (
    <el-col>
      <el-form-item size="large" style="text-align:center;">
        <el-button type="primary" onClick={this.submitForm} 
          loading={this.submitLoading}
        >
          提交
        </el-button>
        <el-button onClick={this.resetForm}>重置</el-button>
      </el-form-item>
    </el-col>
  );
}

function renderFormItem(h, elementList) {
  return elementList.map((scheme) => {
    const config = scheme.__config__;
    const layout = layouts[config.layout];
    
    if (!(this.visibleFormIds.some(it => it == scheme.__config__.formId))) {
      return layouts["emptyDiv"].call(this, h, scheme);
    }
    // 对 tag="tinymce" 特殊处理
    if (scheme.__config__.tag === "tinymce" && true === scheme.__config__.isAsDisplayCmp) {
      return layouts["vHtml"].call(this, h, scheme);
    }

    if (layout) {
      return layout.call(this, h, scheme);
    }
    throw new Error(`没有与${config.layout}匹配的layout`);
  });
}

function renderChildren(h, scheme) {
  const config = scheme.__config__;
  if (!Array.isArray(config.children)) return null;
  return renderFormItem.call(this, h, config.children);
}

function setValue(event, config, scheme) {
  this.$set(config, "defaultValue", event); // 设置v-mode的默认值
  // console.log('setValue from Parser.vue :: ', config, event)
  this.$set(this[this.formConf.formModel], scheme.__vModel__, event);
}

function buildListeners(scheme) {
  const config = scheme.__config__;
  const methods = this.formConf.__methods__ || {};
  const listeners = {};

  // 给__methods__中的方法绑定this和event
  Object.keys(methods).forEach((key) => {
    listeners[key] = (event) => methods[key].call(this, event);
  });
  // 响应 render.js 中的 vModel $emit('input', val)
  listeners.input = (event) => setValue.call(this, event, config, scheme);

  return listeners;
}

/*
  type: and/any 
*/
function logicCalc(arr = [], type = 'and') {
  if (arr.length === 0) return false
  if (type === 'and') {
    return arr.filter(item => !!item).length === arr.length
  }
  if (type === 'any') {
    return arr.filter(item => !!item).length > 0
  }
  return false
}

export default {
  components: {
    render,
  },
  props: {
    formConf: {
      type: Object,
      required: true,
    },
    formLogic: {
      type: Object,
      required: true,
    },
    submitLoading: Boolean,
  },
  data() {
    const data = {
      formConfCopy: deepClone(this.formConf), // 保留一份，用于重置表单
      [this.formConf.formModel]: {}, // 先设置一个空的表单名默认为formData 即：data.formData
      [this.formConf.formRules]: {}, // 先设置一个空的表单rules,默认为rules 即：data.rules
    };
    // 初始化字段s
    this.initFormData(data.formConfCopy.fields, data[this.formConf.formModel]);
    this.buildRules(data.formConfCopy.fields, data[this.formConf.formRules]);
    return data;
  },
  methods: {
    initFormData(componentList, formData) {
      componentList.forEach((cur) => {
        const config = cur.__config__;
        // 每一个字段如果存在v-mode的属性，设置他为默认值
        if (cur.__vModel__) formData[cur.__vModel__] = config.defaultValue;
        // 递归设置, 且传递的同一个formData(平行)
        if (config.children) this.initFormData(config.children, formData);
      });
    },
    buildRules(componentList, rules) {
      componentList.forEach((cur) => {
        const config = cur.__config__;
        // 处理正则的rule规则
        if (Array.isArray(config.regList)) {
          // 检查是否必填
          if (config.required) {
            const required = {
              required: config.required,
              message: cur.placeholder,
            };
            if (Array.isArray(config.defaultValue)) {
              required.type = "array";
              required.message = `请至少选择一个${config.label}`;
            }
            required.message === undefined &&
              (required.message = `${config.label}不能为空`);
            config.regList.push(required);
          }
          rules[cur.__vModel__] = config.regList.map((item) => {
            item.pattern && (item.pattern = eval(item.pattern));
            item.trigger = ruleTrigger && ruleTrigger[config.tag];
            return item;
          });
        }
        if (config.children) this.buildRules(config.children, rules);
      });
    },
    resetForm() {
      // formConfCopy作为formData,this.formConf作为原始数据
      this.formConfCopy = deepClone(this.formConf);
      this.$refs[this.formConf.formRef].resetFields();
    },
    submitForm() {
      this.$refs[this.formConf.formRef].validate((valid) => {
        if (!valid) return false;
        // 触发sumit事件
        this.$emit("submit", this[this.formConf.formModel]);
        return true;
      });
    },
  },
  computed: {
    visibleFormIds() {
      // 对需要控制显示的字段进行解析
      let visibleFormIdList = [] // 显示FormId的列表
      const vModleMap = {} // { `formId`: vModelName }
      this.formConf.fields.forEach(item => {
        if (item.__config__ && item.__config__.formId && item.__vModel__)
        vModleMap[item.__config__.formId] = item.__vModel__
        if (!(this.formLogic.some(it => String(it.form_item_id) === String(item.__config__.formId) ))) {
          visibleFormIdList.push(item.__config__.formId)
        }
      })
      this.formLogic.forEach(item => {
        const controlFormId = item.form_item_id
        const expressionLogic = item.expression === 1 ? 'and' : 'any'
        const tmpCollectBoolean = []
        item.condition_list.forEach(condItem => {
          // 获取对应的vModel的值
          const vModelFormId = condItem.form_item_id
          const vModelValue = this[this.formConf.formModel][vModleMap[vModelFormId]]
          const select_cond = condItem.select_cond
          const select_value = condItem.select_value
          if ('eq' === select_cond) {
            if (Array.isArray(vModelValue)) {
              if (vModelValue.indexOf(select_value) > -1) {
                tmpCollectBoolean.push(true);
              } else {
                tmpCollectBoolean.push(false);
              }
            } else if (vModelValue === select_value) {
              tmpCollectBoolean.push(true);
            } else {
              tmpCollectBoolean.push(false)
            }
          } else if ('nq' === select_cond) {
            if (Array.isArray(vModelValue)) {
              if (vModelValue.indexOf(select_value) === -1) {
                tmpCollectBoolean.push(true)
              } else {
                tmpCollectBoolean.push(false);
              }
            } else if (!(vModelValue === select_value)) {
              tmpCollectBoolean.push(true)
            } else {
              tmpCollectBoolean.push(false)
            }
          }
        })
        // 处理显示逻辑
        if (logicCalc(tmpCollectBoolean, expressionLogic)) {
          if (!visibleFormIdList.some(item => item == controlFormId))
            visibleFormIdList.push(controlFormId)
        } else {
          if (visibleFormIdList.some(item => item == controlFormId))
            visibleFormIdList = visibleFormIdList.filter(it => !(it === controlFormId))
        }
        // console.log('visibleFormIdList:', JSON.stringify(visibleFormIdList))
      })
      // 计算显示与否的逻辑
      return visibleFormIdList
    }
  },
  render(h) {
    // jsx的render方法
    return renderFrom.call(this, h);
  },
};
</script>
